/**
 * 
 */
package me.nujoug.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.protocol.BasicHttpContext;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.util.Log;

/**
 * @author juguo Basic class to handle http request
 */
public class HttpClientHelper {
	private static final String TAG = "HttpClientHelper";
	private static AndroidHttpClient mHttpclient;
	private static BasicHttpContext mContext;
	private static final String UA = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.76 Safari/537.36";
	private static Pattern encodingPattern;
	static {
		mHttpclient = AndroidHttpClient.newInstance(UA);
		mContext = new BasicHttpContext();
		mContext.setAttribute(ClientContext.COOKIE_STORE,
				new BasicCookieStore());
		encodingPattern = Pattern.compile("charset=.*");
	}

	private HttpClientHelper() {
	}

	public static String GetPageContent(String url) {
		return GetPageContent(url, null, false);
	}

	public static String GetPageContent(String url, String referrerUrl){
		return GetPageContent(url, referrerUrl, false);
	}
	
	public static String GetPageContent(String url, String referrerUrl, boolean isAjaxRequest) {
		Log.v(TAG, "Start GetPageCountnt:" + url);
		if(url == null || !url.startsWith("http"))
			return "";
		final HttpGet getRequest = new HttpGet(url);
		if (referrerUrl != null && !referrerUrl.isEmpty())
			getRequest.setHeader("Referer", referrerUrl);
		if(isAjaxRequest)
			getRequest.setHeader("X-Requested-With", "XMLHttpRequest");
		try {
			HttpResponse response = mHttpclient.execute(getRequest, mContext);
			final int statusCode = response.getStatusLine().getStatusCode();
			Log.v(TAG, "HttpStatus:" + statusCode);
			if (statusCode != HttpStatus.SC_OK) {
				Log.v(TAG, "Error" + statusCode + "while requesting " + url);
				return null;
			}
			final HttpEntity entity = response.getEntity();
			String contentType = getCharset(entity.getContentType().toString());
			if (entity != null) {
				InputStream inputStream = null;
				try {
					inputStream = entity.getContent();
					return CvtStreamtoString(inputStream, contentType);
				} finally {
					if (inputStream != null) {
						inputStream.close();
					}
					entity.consumeContent();
				}
			}
		} catch (IOException e) {
			getRequest.abort();
			Log.v(TAG, "I/O error while reading stream from " + url, e);
		} catch (IllegalStateException e) {
			getRequest.abort();
			Log.w(TAG, "Incorrect URL: " + url);
		} catch (Exception e) {
			getRequest.abort();
			Log.w(TAG, "Error while requesting from " + url, e);
		}
		return null;
	}

	public static String GetPostContent(String url, String referrerUrl,
			List<NameValuePair> postData, List<NameValuePair> headData) {
		Log.v(TAG, "Start GetPostContent:" + url);
		if(url == null || !url.startsWith("http"))
			return "";
		final HttpPost request = new HttpPost(url);
		if (referrerUrl != null && !referrerUrl.isEmpty())
			request.setHeader("Referer", referrerUrl);
		if (headData != null) {
			for (NameValuePair nameValuePair : headData) {
				request.setHeader(nameValuePair.getName(),
						nameValuePair.getValue());
			}
		}
		try {
			if (postData != null)
				request.setEntity(new UrlEncodedFormEntity(postData, "UTF-8"));
			request.setHeader("Content-type", "application/x-www-form-urlencoded");
			HttpResponse response = mHttpclient.execute(request, mContext);
			final int statusCode = response.getStatusLine().getStatusCode();
			Log.v(TAG, "HttpStatus:" + statusCode);
			if (statusCode != HttpStatus.SC_OK) {
				Log.v(TAG, "Error" + statusCode + "while requesting " + url);
				return null;
			}
			final HttpEntity entity = response.getEntity();
			String contentType = getCharset(entity.getContentType().toString());
			if (entity != null) {
				InputStream inputStream = null;
				try {
					inputStream = entity.getContent();
					return CvtStreamtoString(inputStream, contentType);
				} finally {
					if (inputStream != null) {
						inputStream.close();
					}
					entity.consumeContent();
				}
			}
		} catch (IOException e) {
			request.abort();
			Log.v(TAG, "I/O error while reading stream from " + url, e);
		} catch (IllegalStateException e) {
			request.abort();
			Log.w(TAG, "Incorrect URL: " + url);
		} catch (Exception e) {
			request.abort();
			Log.w(TAG, "Error while requesting from " + url, e);
		}
		return null;
	}

	public static Bitmap GetBitmap(String url, String referrerUrl) {
		if(url == null || !url.startsWith("http"))
			return null;
		final HttpGet getRequest = new HttpGet(url);
		if (referrerUrl != null && !referrerUrl.isEmpty())
			getRequest.setHeader("Referer", referrerUrl);
		try {
			HttpResponse response = mHttpclient.execute(getRequest, mContext);
			final int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				Log.v(TAG, "Error" + statusCode + "while requesting " + url);
				return null;
			}
			final HttpEntity entity = response.getEntity();
			if (entity != null) {
				InputStream inputStream = null;
				try {
					inputStream = entity.getContent();
					return BitmapFactory.decodeStream(inputStream);
				} finally {
					if (inputStream != null) {
						inputStream.close();
					}
					entity.consumeContent();
				}
			}
		} catch (IOException e) {
			getRequest.abort();
			Log.v(TAG, "I/O error while reading stream from " + url, e);
		} catch (IllegalStateException e) {
			getRequest.abort();
			Log.w(TAG, "Incorrect URL: " + url);
		} catch (Exception e) {
			getRequest.abort();
			Log.w(TAG, "Error while requesting from " + url, e);
		}
		return null;
	}

	private static String getCharset(String str) {
		Matcher matcher = encodingPattern.matcher(str);
		if (matcher.find())
			return matcher.group(0).split("charset=")[1];
		return "utf-8";
	}

	private static String CvtStreamtoString(InputStream is, String contentType)
			throws IOException {
		String ret = "";
		InputStreamReader isr = new InputStreamReader(is, contentType);
		BufferedReader br = new BufferedReader(isr);
		String tmp = br.readLine();
		while (tmp != null) {
			ret += tmp;
			tmp = br.readLine();
		}
		br.close();
		return ret;
	}

	/**
	 * just made a default http request, by default doesn't extract the response
	 * 
	 * @author juguo
	 * 
	 */
	public static class HttpHelperTask extends AsyncTask<String, Void, Object> {

		@Override
		protected Object doInBackground(String... params) {
			if (params.length > 0 && params[0] != null
					&& params[0].startsWith("http")) {
				if (params.length > 1 && params[1] != null
						&& params[1].startsWith("http"))
					return HttpClientHelper
							.GetPageContent(params[0], params[1]);
				else
					return HttpClientHelper.GetPageContent(params[0], null);
			}
			return null;
		}

		@Override
		protected void onPostExecute(Object result) {
			super.onPostExecute(result);

		}

	}
}
